#include "excelutils_p.h"

#include "rapidjson/document.h"

#include <QList>
#include <rapidjson/rapidjson.h>
#include <xlsxdocument.h>
#include <xlsxworksheet.h>
ExcelUtilsPrivate::ExcelUtilsPrivate(ExcelUtils* p)
	: p(p){}

bool ExcelUtilsPrivate::exportXlsx(const QList<QStringList>& list, const QString& path, const QString& sheetName) const
{
	QXlsx::Document doc;

	// 新建工作表
	if (!doc.addSheet(sheetName))
	{
		return false;// 添加失败
	}
	// 写入数据
	for (int row = 0; row < list.size(); ++row)
	{
		const QStringList& rowData = list.at(row);
		for (int col = 0; col < rowData.size(); ++col)
		{
			doc.write(row + 1, col + 1, rowData.at(col));
			// 注意 QXlsx 的行列是从 1 开始
		}
	}

	// 保存文件
	return doc.saveAs(path);
}
bool ExcelUtilsPrivate::exportXlsx(const QString& jsonStr, const QString& path, const QString& sheetName) const
{
	QXlsx::Document doc;
	doc.addSheet(sheetName);
	doc.selectSheet(sheetName);

	rapidjson::Document jsonDoc;
	jsonDoc.Parse(jsonStr.toUtf8().constData());
	if (jsonDoc.HasParseError() || !jsonDoc.IsArray())
		return false;

	const auto& arr = jsonDoc.GetArray();
	if (arr.Empty()) return false;

	// 写表头
	int col = 1;
	for (const auto& field : arr[0].GetObject())
	{
		doc.write(1, col, QString::fromUtf8(field.name.GetString()));
		col++;
	}

	// 写数据
	int row = 2;
	for (const auto& item : arr)
	{
		col = 1;
		for (const auto& field : item.GetObject())
		{
			if (field.value.IsString())
				doc.write(row, col, QString::fromUtf8(field.value.GetString()));
			else if (field.value.IsInt())
				doc.write(row, col, field.value.GetInt());
			else if (field.value.IsDouble())
				doc.write(row, col, field.value.GetDouble());
			else if (field.value.IsBool())
				doc.write(row, col, field.value.GetBool() ? "true" : "false");
			else
				doc.write(row, col, ""); // 其他情况忽略
			col++;
		}
		row++;
	}

	return doc.saveAs(path);
}


QList<QStringList> ExcelUtilsPrivate::fromXlsx(const QString& path, const QString& sheetName) const
{
	QXlsx::Document doc(path);
	if (!doc.selectSheet(sheetName))
	{
		return {};
	}
	const QXlsx::CellRange range = doc.dimension(); // 获取有效区域
	QList<QStringList> result;

	for (int row = range.firstRow(); row <= range.lastRow(); ++row) {
		QStringList rowValues;
		for (int col = range.firstColumn(); col <= range.lastColumn(); ++col) {
			auto cell = doc.cellAt(row, col);
			if (cell) {
				rowValues << cell->value().toString();
			} else {
				rowValues << ""; // 保持列数对齐
			}
		}
		result << rowValues;
	}

	return result;
}